<?php
/**
 * Created by PhpStorm.
 * User: wangliang
 * Date: 2018/12/12
 * Time: 9:28 PM
 */

/**
 * @param $val 值
 * @param $data 数组
 * @param $key 键名
 */
function is_selected($val, $data, $key, $type = 1)
{
    if (!empty($data[$key])) {
        if ($data[$key] == $val) {
            if ($type == 1) {
                echo 'selected';
            } else {
                echo 'checked';
            }
        }
    }
}

/**
 * @param $time 时间戳
 * @param string $format 时间格式
 *
 * @return false|string
 */
function toDate($time, $format = 'Y-m-d H:i:s')
{
    if (empty($time)) {
        return '';
    }
    $format = str_replace('#', ':', $format);
    return date($format, $time);
}

/**
 * 根据产品id获取产品的总库存
 *
 * @param $goods_id
 *
 * @return mixed
 */
function houseGoodsTotalNum($goods_id)
{
    $list = DB::table('storehouse_detailed')->where('goods_id', '=', $goods_id)->sum('stock_num');
    return $list;
}

/**
 * 根据商品编号，获取未发货订单的数量
 *
 * @param $goods_id
 */
function subscribe_goods($goods_id)
{
    $map['deliver_state'] = 0;
    $map['goods_id'] = $goods_id;
    $list = DB::table('user_order_detailed')->where($map)->sum('goods_num');
    return $list;
}

/**
 * 尺寸
 * @return array
 */
function fun_size($id)
{
    $list = trans('symessages.goods_size');
    $data = [];
    $i = 1;
    foreach ($list as $value) {
        $data[$i] = $value;
        $i++;
    }
    if (empty($data[$id])) {
        return '无';
    }
    return $data[$id];
}

/**
 * 把尺寸更换成数组
 *
 * @param $id
 *
 * @return array
 */
function get_size_list($id)
{
    $list = fun_size($id);
    $ret = explode("・", $list);
    return $ret;
}

/**
 * 颜色
 * @return array
 */
function fun_colors($id)
{
    $list = trans('symessages.goods_color');
    $data = [];
    $i = 1;
    foreach ($list as $value) {
        $data[$i] = $value;
        $i++;
    }
    if (empty($data[$id])) {
        return '无';
    }
    return $data[$id];
}

/**
 * 根据分类的id，返回分类的名称
 *
 * @param $id
 *
 * @return mixed|string
 */
function fun_category($id)
{
    if (Cache::has('fun_category')) {
        $data = Cache::get('fun_category');
    } else {
        $list = DB::table('category_master')->select('category_id', 'category_name', 'category_code')->get();
        $data = [];
        foreach ($list as $value) {
            $data[$value->category_id] = $value->category_name;
        }
        Cache::put('fun_category', $data, '60');
    }
    if (empty($data[$id])) {
        return '无';
    }
    return $data[$id];

}


/**
 * 根据公司的id，返回公司的名称
 *
 * @param $id
 *
 * @return mixed|string
 */
function fun_corp($id)
{
    if (Cache::has('fun_corp')) {
        $data = Cache::get('fun_corp');
    } else {
        $list = DB::table('corp_master')->select('corp_id', 'corp_name', 'corp_catelogue')->get();
        $data = [];
        foreach ($list as $value) {
            $data[$value->corp_id] = $value->corp_name;
        }
        Cache::put('fun_corp', $data, '60');
    }
    if (empty($data[$id])) {
        return '无';
    }
    return $data[$id];

}

/**
 * 根据公司的id，返回公司的名称
 *
 * @param $id
 *
 * @return mixed|string
 */
function fun_shop($id)
{
    if (Cache::has('fun_shop')) {
        $data = Cache::get('fun_shop');
    } else {
        $list = DB::table('shop_master')->select('shop_id', 'shop_name', 'shop_kana')->get();
        $data = [];
        foreach ($list as $value) {
            $data[$value->shop_id] = $value->shop_name;
        }
        Cache::put('fun_shop', $data, '60');
    }
    if (empty($data[$id])) {
        return '无';
    }
    return $data[$id];

}

/**
 * 获取仓库名称
 * @param $id
 *
 * @return mixed|string
 */
function fun_house($id)
{
    if (Cache::has('fun_house')) {
        $data = Cache::get('fun_house');
    } else {
        $list = DB::table('storehouse_master')->select('storehouse_id', 'storehouse_name', 'storehouse_type')->get();
        $data = [];
        foreach ($list as $value) {
            $data[$value->storehouse_id] = $value->storehouse_name;
        }
        Cache::put('fun_house', $data, '60');
    }
    if (empty($data[$id])) {
        return '无';
    }
    return $data[$id];

}


/**
 * 返回
 *
 * @param bool $id
 *
 * @return array|\Illuminate\Contracts\Translation\Translator|null|string
 */
function clearing_from($id = false)
{
    $data = trans('symessages.clearing_form');
    if ($id === false) {
        return $data;
    } else {
        return $data[$id];
    }
}

/**
 * 数组 转 对象
 *
 * @param array $arr 数组
 *
 * @return object
 */
function array_to_object($arr)
{
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }

    return (object)$arr;
}

/**
 * 对象 转 数组
 *
 * @param object $obj 对象
 *
 * @return array
 */
function object_to_array($obj)
{
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }

    return $obj;
}

/**
 * 二维数组排序
 *
 * @param $arr
 * @param $keys
 * @param string $type
 *
 * @return array
 */
function lyx_array_sort($arr, $keys, $type = 'desc')
{
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($key_value);
    } else {
        arsort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}

/**
 * 进出库管理
 *
 * @param $data 进出库明细，必要字段【order_id,goods_id,num】
 * @param $type 0-进货，1-出库，2-盘点,3-库存调整
 * @param $source 0用户 1供应商
 * @param $storehouse_id 仓库id
 *
 * @return bool
 */
function in_out_log($data, $type, $source, $storehouse_id)
{
    $saveData = [];
    if (count($data) > 0) {

        DB::beginTransaction();

        foreach ($data as $value) {
            //--仓库日志明细
            $LinData['order_id'] = $value['order_id'];
            $LinData['goods_id'] = $value['goods_id'];
            $LinData['type'] = $type;
            $LinData['num'] = $value['num'];
            $LinData['model_id'] = $value['model_info']['goods_model_id'];
            $LinData['color'] = $value['model_info']['color_name'];
            $LinData['size'] = $value['model_info']['size_name'];
            $LinData['source'] = $source;
            $LinData['storehouse_id'] = $storehouse_id;

            //--仓库明细数据
            $houseDetData['storehouse_id'] = $storehouse_id;
            $houseDetData['goods_id'] = $value['goods_id'];
            $houseDetData['stock_num'] = $value['num'];
            $houseDetData['purchase_num'] = empty($value['purchase_num']) ? 0 : $value['purchase_num'];
            $houseDetData['update_time'] = toDate(time());

            $ret_one = DB::table('storehouse_detailed_size')->where(['goods_id' => $value['goods_id'], 'model_id' => $value['model_info']['goods_model_id']])->first();
            $detailed_size_info = $ret_one;
            if ($ret_one != false) {
                $ret_one = object_to_array($ret_one);
                $LinData['before_stock_num'] = $ret_one['num'];
                $ret_one['update_time'] = toDate(time());
                //--库存数量的增加和减少
                if ($type === 0) {//-新增
                    $ret_one['num'] = $ret_one['num'] + $value['num'];
                    //                    $ret['good_num'] = $ret['good_num']+$value['num'];
                } else if ($type === 1) {//出库
                    $ret_one['num'] = $ret_one['num'] - $value['num'];
                    //                    $ret['good_num'] = $ret['good_num'] - $value['num'];
                } else if ($type == 2) {
                    $ret_one['num'] = $value['num'];
                    //                        $ret['good_num'] =   $value['num'];
                } else if ($type == 3) {
                    if ($value['goods_type'] == 1) {
                        $ret_one['num'] = $ret_one['num'] - $value['num'];
                        $ret_one['bad_num'] = $ret_one['bad_num'] + $value['num'];
                    } else {
                        $ret_one['num'] = $ret_one['num'] + $value['num'];
                        $ret_one['bad_num'] = $ret_one['bad_num'] - $value['num'];
                    }
                }
                DB::table('storehouse_detailed_size')->where(['goods_id' => $value['goods_id'], 'model_id' => $value['model_info']['goods_model_id']])->update($ret_one);
                $LinData['after_stock_num'] = $ret_one['num'];
            } else {

                $LinData['before_stock_num'] = 0;
                $LinData['after_stock_num'] = $value['num'];

                $houseSizeData['storehouse_id'] = $storehouse_id;
                $houseSizeData['create_time'] = toDate(time());
                $houseSizeData['goods_id'] = $value['goods_id'];
                $houseSizeData['model_id'] = $value['model_info']['goods_model_id'];
                $houseSizeData['color'] = $value['model_info']['color_name'];
                $houseSizeData['size'] = $value['model_info']['size_name'];
                $houseSizeData['num'] = $value['num'];
                DB::table('storehouse_detailed_size')->insert($houseSizeData);
            }


            $ret = DB::table('storehouse_detailed')->where('goods_id', '=', $value['goods_id'])->first();
            if ($ret != false) {
                $ret = object_to_array($ret);
                //--库存数量的增加和减少
                if ($type === 0) {//-新增
                    $ret['stock_num'] = $ret['stock_num'] + $value['num'];
                    //                    $ret['good_num'] = $ret['good_num']+$value['num'];
                } else if ($type === 1) {//出库
                    $ret['stock_num'] = $ret['stock_num'] - $value['num'];
                    //                    $ret['good_num'] = $ret['good_num'] - $value['num'];
                } else if ($type == 2) {
                    if ($detailed_size_info != false) {
                        $ret['stock_num'] = $ret['stock_num'] - $detailed_size_info->num + $value['num'];
                    } else {
                        $ret['stock_num'] = $ret['stock_num'] + $value['num'];
                    }
                    //                        $ret['good_num'] =   $value['num'];
                } else if ($type == 3) {
                    $LinData['goods_type'] = $value['goods_type'];
                    $LinData['remark'] = empty($value['remark']) ? '' : $value['remark'];
                    if ($value['goods_type'] == 1) {
//                        $ret['stock_num'] = $ret['stock_num'] + $value['num'];
                    } else {
//                        $ret['stock_num'] = $ret['stock_num'] + $value['num'];
                    }
                }
                DB::table('storehouse_detailed')->where('goods_id', '=', $value['goods_id'])->update($ret);
            } else {
                $houseDetData['create_time'] = toDate(time());
                DB::table('storehouse_detailed')->insert($houseDetData);
            }


            $saveData[] = $LinData;
        }
        DB::table('inout_log')->insert($saveData);
        DB::commit();
        return true;

    }
    return false;
}

/*
 * 递归无限菜单
 */
function findChild(&$arr, $id)
{
    $childs = array();
    foreach ($arr as $k => $v) {
        if ($v['pid'] == $id) {
            $childs[] = $v;
        }
    }
    return $childs;
}

//树形结构页面函数
function build_tree($rows, $root_id)
{
    $childs = findChild($rows, $root_id);
    if (empty($childs)) {
        return null;
    }
    foreach ($childs as $k => $v) {
        $rescurTree = build_tree($rows, $v['id']);
        if (null != $rescurTree) {
            $childs[$k]['childs'] = $rescurTree;
        }
    }
    return $childs;
}

function getTreeHtml($data, $html = '')
{
    if (!empty($data)) {
        foreach ($data as $key => $value) {
            if ($value['category_image'] != '') {
                $img = '<img style="width: 20px;height: 20px;" src="' . $value['category_image'] . '"/>';
            } else {
                $img = '';
            }
            $child = '';
            if (isset($value['childs'])) {
                $child = $value['childs'];
            }
            $html = $html . '<li data-title="'.$value["category_name"].'">
					<span>' . $img . $value['category_name'] . '</span>
					<a href="#" class="ajax-list" data-toggle="modal" data-target="#exampleModal" data-pid="' . $value["id"] . '" data-type="add">
						<i class="iconfont hd-tianjia1"></i>
					</a>
					<a href="#" class="ajax-list" data-toggle="modal" data-target="#exampleModal" data-id="' . $value["id"] . '" data-type="edit">
						<i class="iconfont hd-bianji"></i>
					</a>
					<a href="#" class="ajax-list lyx_del"  data-id="' . $value["id"] . '">
                        <i class="iconfont hd-shanchu1"></i>
                    </a>'
                . getTreeHtml($child) . '</li>';
        }
    }
    if ($html != '') {
        return '<ul>' . $html . '</ul>';
    } else {
        return $html;
    }
}

/** 获取产品分类的数据
 * @return array|null
 */
function getCategoryTreeData()
{
    $list = DB::table('category_master')
        ->orderBy("bpath")
        ->select(DB::raw("category_id as id,pid,category_name,category_en,sort,delete_flg,category_image,concat(path,'-',category_id) as bpath"))
        ->where(['delete_flg' => 0])
        ->get()->map(function ($value) {
            return (array)$value;
        })->toArray();
    if ($list != FALSE) {
        $tree = build_tree($list, 0);
    } else {
        return [];
    }
    $tree = lyx_array_sort($tree, 'sort');
    return $tree;
}

/**
 * 返回订单发货状态名称
 * @param $id
 *
 * @return mixed
 */
function outHouseState($id){
    $data = trans('symessages.post_goods_state');
    return $data[$id];
}